package cn.zch.soft.controller.xbqrmaker;
import cn.zch.soft.model.DeviceQrcodeImage;
import cn.zch.soft.service.DeviceQrcodeImageService;
import cn.zch.soft.util.file.zip.ZipUtils;
import cn.zch.soft.util.qrcode.utils.Convert;
import cn.zch.soft.util.qrcode.utils.DesUtil;
import cn.zch.soft.util.qrcode.utils.QrCodeEncoderHandler;
import cn.zch.soft.util.qrcode.utils.StringUtil;
import cn.zch.soft.util.qrcode.utils.qartutil.DateUtil;
import cn.zch.soft.util.thread.SleepMoment;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author zchcpy
 */
@Slf4j
@Controller
@RequestMapping("/qrmaker")
public class Xbqrmaker {
  @Resource
  private DeviceQrcodeImageService deviceQrcodeImageService;
  private static final String UPLOAD_PATH = "File/image/upload";
  @RequestMapping("/index")
  public ModelAndView index(@RequestParam("id") int id, @RequestParam("from") String from,
                            //
                            HttpServletRequest request, HttpServletResponse response, Model model) {
    log.info("index mode:" + model);
    return new ModelAndView("javaQr/qrMake");
  }
  /**
   * String contents = "http://" + serverUrl + "/qrdt.do?dsn=" + selectDeviceSn;
   * String contents = "http://" + serverUrl + "/q.do?v=2&s=" + i;
   *
   * @param qrSize         int
   * @param colorContent   int
   * @param colorBg        int
   * @param correctLevel   int
   * @param imgFormat      String
   * @param serverUri      String
   * @param colorBorder    int
   * @param logoPath       String
   * @param begindeviceNum int
   * @param enddeviceNum   int
   * @param versionNumber  String
   * @param devicename     int
   * @param request        HttpServletRequest
   * @param response       HttpServletResponse
   * @param model          Model
   * @return Map
   */
  @ResponseBody
  @RequestMapping("/make")
  public Map<Object, Object> make(@RequestParam("qrSize") int qrSize, @RequestParam("colorContent") int colorContent,/*分行*/
                                  @RequestParam("colorBg") int colorBg, @RequestParam("correctLevel") int correctLevel,/*分行*/
                                  @RequestParam("imgFormat") String imgFormat, @RequestParam("serverUri") String serverUri,/*分行*/
                                  @RequestParam("colorBorder") int colorBorder, @RequestParam("logoPath") String logoPath,/*分行*/
                                  @RequestParam("begindeviceNum") int begindeviceNum, @RequestParam("enddeviceNum") int enddeviceNum,/*分行*/
                                  @RequestParam("versionNumber") String versionNumber, @RequestParam("devicename") int devicename,/*分行*/
                                  HttpServletRequest request, HttpServletResponse response, Model model) {
    HashMap<Object, Object> map = new HashMap<>();
    try {
      String[] split = serverUri.split("=");
      String url = split[1];
      String equalUrl = split[0];
      QrCodeEncoderHandler handler = new QrCodeEncoderHandler();
      long currentTimeMillis = System.currentTimeMillis();
      String property = System.getProperty("user.dir");
      String thisTimePath = UPLOAD_PATH + File.separator + DateUtil.getPathdate() + currentTimeMillis +
        //
        "_B" + begindeviceNum + "_E" + enddeviceNum + "_" + StringUtil.getTimeWithPureNumber() + File.separator;
      for (int i = begindeviceNum; i <= enddeviceNum; i++) {
        String sn = Convert.intToHexString(i, 16).toUpperCase();
        String selectDeviceSn = "";
        String qrContent = "";
        selectDeviceSn = DesUtil.encrypt(sn);
        if ("V1".equals(versionNumber)) {
          qrContent = "http:" + "//" + url + "/qrdt.do?dsn=" + selectDeviceSn;
        }
        if ("V2".equals(versionNumber)) {
          qrContent = "http://" + url + "/q.do?v=2&s=" + i;
        }
        if ("V3".equals(versionNumber)) {
          qrContent = "http://" + url + "/qrdt.do?dsn=" + i;
        }
        log.info("qrContent = " + qrContent);
        StringBuffer requestUrl = request.getRequestURL();
        String requestUri = request.getRequestURI();
        // 网络地址 String url = "/static/img/qr/"
        String replace = requestUrl.toString().replace(requestUri, "");
        String httpUrl = replace + "/" + thisTimePath + i + "." + imgFormat;
        //本机硬盘位置
        // String filePathRoot = ClassUtils.getDefaultClassLoader().getResource("static").getPath()
        //String filePathRoot = request.getSession().getServletContext().getRealPath()
        Path directory = Paths.get(thisTimePath);
        //判断是否存在该文件夹，若不存在则创建文件夹
        if (!Files.exists(directory)) {
          Files.createDirectories(directory);
        }
        String hardDiskUrl = property + "/" + thisTimePath + i + "." + imgFormat;
        String replace1 = hardDiskUrl.replace("\\", "/");
        handler.encode(qrContent, qrSize, qrSize, hardDiskUrl, null, colorContent, colorBg, i, imgFormat, devicename);
        DeviceQrcodeImage deQrImg = new DeviceQrcodeImage();
        deQrImg.setDate(StringUtil.getNowTimeFortest());
        deQrImg.setDeviceId(String.valueOf(i));
        deQrImg.setDeviceNun(sn);
        deQrImg.setDeviceSn(selectDeviceSn);
        deQrImg.setHardDiskUrl(replace1);
        deQrImg.setQrcodeVisitUrl(qrContent);
        deQrImg.setHttpUrl(httpUrl);
        deQrImg.setEqualUrl(Integer.valueOf(equalUrl));
        deQrImg.setVersionNumber(versionNumber);
        deviceQrcodeImageService.insertSelective(deQrImg);
      }
    }
    catch (Exception e) {
      log.error(e.getMessage(), e);
    }
    map.put("name", "二维码生成完毕");
    return map;
  }
  /**
   * @param request  HttpServletRequest
   * @param response HttpServletResponse
   * @param model    Model
   * @return ModelAndView
   */
  @RequestMapping("/qrDownloadBatch")
  public ModelAndView qrDownloadBatch(HttpServletRequest request, HttpServletResponse response, Model model) {
    ModelAndView modelAndView = new ModelAndView("javaQr/qrDownloadBatch");
    log.info("modelAndView:" + modelAndView);
    return modelAndView;
  }
  /**
   * List<DeviceQrcodeImage>
   *
   * @param begindeviceNum Integer
   * @param enddeviceNum   Integer
   * @param equalUrl       Integer
   * @param request        request
   * @param response       HttpServletResponse
   * @param model          Model
   */
  @ResponseBody
  @RequestMapping("/query")
  public String query(Integer begindeviceNum, Integer enddeviceNum, String equalUrl,
                      //
                      HttpServletRequest request, HttpServletResponse response, Model model) {
    // PrintWriter p = null;
    try {
      // print("begindeviceNum = " + begindeviceNum);
      // print("enddeviceNum = " + enddeviceNum);
      // print("equalUrl = " + equalUrl);
      // print("model = " + model);
      // p = response.getWriter();
      int equalUrlIndex = Integer.parseInt(equalUrl.split("#")[0]);
      List<DeviceQrcodeImage> deviceQrcodeImageList = deviceQrcodeImageService.selectBydevice(begindeviceNum, enddeviceNum, equalUrlIndex);
      for (DeviceQrcodeImage deviceQrcodeImage : deviceQrcodeImageList) {
        // print("deviceQrcodeImage = " + deviceQrcodeImage);
        break;
      }
      model.addAttribute("deviceQrcodeImageList", deviceQrcodeImageList);
      // p.print(deviceQrcodeImageList);
      String returnJsonStr = JSON.toJSONString(deviceQrcodeImageList);
      JSONArray returnJsonArray = JSON.parseArray(returnJsonStr);
      // print("returnJsonArray = " + returnJsonArray);
      return returnJsonArray.toJSONString();
    }
    catch (Exception e) {
      log.error(e.getMessage(), e);
      return "-1";
    }
  }
  @RequestMapping("/file/download")
  public void fileDownload(HttpServletRequest request, HttpServletResponse response, Model model) {
    String beginDeviceNumStr = request.getParameter("begindeviceNum");
    String endDeviceNumStr = request.getParameter("enddeviceNum");
    String equalUrlStr = request.getParameter("equalUrl");
    String equalUrlText = request.getParameter("equalUrlText");
    log.info("equalUrlText:{}", equalUrlText);
    Integer beginDeviceNum = null;
    Integer endDeviceNum = null;
    int equalUrlIndex = 0;
    if (!StringUtils.isEmpty(beginDeviceNumStr)) {
      beginDeviceNum = Integer.parseInt(beginDeviceNumStr);
    }
    if (!StringUtils.isEmpty(endDeviceNumStr)) {
      endDeviceNum = Integer.parseInt(endDeviceNumStr);
    }
    if (!StringUtils.isEmpty(equalUrlStr)) {
      equalUrlIndex = Integer.parseInt(equalUrlStr.split("#")[0]);
    }
    List<DeviceQrcodeImage> deviceQrcodeImageList = deviceQrcodeImageService.selectBydevice(beginDeviceNum, endDeviceNum, equalUrlIndex);
    int size = deviceQrcodeImageList.size();
    log.info("共有size = " + size + "个文件.");
    String beginDeviceId = deviceQrcodeImageList.get(0).getDeviceId();
    String endDeviceId = deviceQrcodeImageList.get(deviceQrcodeImageList.size() - 1).getDeviceId();
    DeviceQrcodeImage deviceQrcodeImage = deviceQrcodeImageList.get(0);
    String hardDiskUrl = deviceQrcodeImage.getHardDiskUrl();
    String[] hardDiskUrlSplitStr = hardDiskUrl.split("/");
    int hardDiskUrlSplitStrLength = hardDiskUrlSplitStr.length;
    log.info("hardDiskUrlSplitStrLength = " + hardDiskUrlSplitStrLength);
    String dayOfHardDiskUrl = hardDiskUrlSplitStr[hardDiskUrlSplitStrLength - 2];
    String doIndexDayOfHardDiskUrl = "/" + dayOfHardDiskUrl + "/";
    int dayIndexOfHardDiskUrl = hardDiskUrl.indexOf(doIndexDayOfHardDiskUrl);
    String dayDicUrl = hardDiskUrl.substring(0, dayIndexOfHardDiskUrl) + "/";
    // 存储路径
    String dayOfHardDiskUrlToSave = hardDiskUrlSplitStr[hardDiskUrlSplitStrLength - 3];
    String doIndexDayOfHardDiskUrlToSave = "/" + dayOfHardDiskUrlToSave + "/";
    int dayIndexOfHardDiskUrlToSave = hardDiskUrl.indexOf(doIndexDayOfHardDiskUrlToSave);
    String dayDicUrlToSave = hardDiskUrl.substring(0, dayIndexOfHardDiskUrlToSave) + "/";
    // FileOutputStream fos1 = new FileOutputStream("E:/myTest01.zip")
    FileOutputStream fos1 = null;
    //待下载文件名
    String fileName = equalUrlStr.split("#")[1] + "_B" + beginDeviceId + "_E" + endDeviceId + ".zip";
    log.info("fileName:{}", fileName);
    String fileFullName = dayDicUrlToSave + fileName;
    log.info("fileFullName:{}", fileFullName);
    try {
      fos1 = new FileOutputStream(fileFullName);
    }
    catch (FileNotFoundException e) {
      log.warn(e.getMessage());
      log.warn("无法找到文件:{}", fileFullName);
      return;
    }
    ZipUtils.toZip(dayDicUrl, fos1, true);
    // 等待5S压缩时间
    SleepMoment.sleep(5000);
    //删除文件及文件夹
    // deviceQrcodeImageService.deleteLIKEhttpurl(sub)
    // delFile(new File(property + "/" + UPLOAD_PATH))
    //设置为png格式的文件
    response.setHeader("content-type", "tapplication/octet-stream");
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    byte[] buff = new byte[4096];
    //创建缓冲输入流
    try (OutputStream outputStream = response.getOutputStream(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileFullName))) {
      int read = bis.read(buff);
      //通过while循环写入到指定了的文件夹中
      while (read != -1) {
        outputStream.write(buff, 0, buff.length);
        outputStream.flush();
        read = bis.read(buff);
      }
    }
    catch (IOException e) {
      //出现异常返回给页面失败的信息
      log.error(e.getMessage(), e);
    }
  }
}

